package com.zhiwang.planet

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import cn.bmob.v3.Bmob
import com.bun.miitmdid.core.JLibrary
import com.bytedance.sdk.openadsdk.TTAdConfig
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.cmcm.cmgame.CmGameSdk
import com.cmcm.cmgame.gamedata.CmGameAppInfo
import com.iBookStar.views.YmConfig
import com.liulishuo.filedownloader.FileDownloader
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import com.zhiwang.planet.di.component.AppComponent
import com.zhiwang.planet.di.component.DaggerAppComponent
import com.zhiwang.planet.di.module.AppModule
import com.zhiwang.planet.download.filedownloader.FileDownLoadManager
import com.zhiwang.planet.mvvm.viewmodel.NetWorkViewModel
import com.zhiwang.planet.sdk.bytedance_tinygame.TinyGameImageLoader
import com.zhiwang.planet.ui.MainActivity
import com.zhiwang.planet.ui.loginv2.LoginFillSmsActivity
import com.zhiwang.planet.ui.loginv2.LoginV2Activity
import com.zhiwang.planet.ui.loginv2.WxLoginActivity
import com.zhiwang.planet.util.*
import io.reactivex.plugins.RxJavaPlugins
import javax.inject.Inject

class App : Application(),ViewModelStoreOwner {



    companion object{
       lateinit var  instance :App
    }

    override fun getViewModelStore(): ViewModelStore = appViewModelStoreOwner


    lateinit var viewModelFactory:ViewModelProvider.Factory

    lateinit var appComponent: AppComponent
    @Inject
    lateinit var networkViewModel: NetWorkViewModel

    lateinit var appViewModelStoreOwner: ViewModelStore

    override fun onCreate() {
        super.onCreate()
        instance = this
        FileDownloader.setup(this)
        Toaster.init(this)
        FileDownLoadManager.holdContext(this)
        TokenManager.init(this)
        AppHelper.init(this)
        Bmob.initialize(this, "bdb1fe705f0b81a78afc4953621ebfa9")
        appComponent = DaggerAppComponent.builder()
                .appModule(AppModule(this))
                .build()
        appComponent.inject(this)
        registerActivityLifecycle()

        if (BuildConfig.DEBUG.not()) {
            UMConfigure.init(this, Store.UMENG_APP_KEY, ChannelUtil.getChannel(this), UMConfigure.DEVICE_TYPE_PHONE, null)
            //bugly crash report

        }

        val strategy = CrashReport.UserStrategy(this)
        strategy.appChannel = ChannelUtil.getChannel(this)
        strategy.appVersion = BuildConfig.VERSION_NAME
        strategy.appReportDelay = 2000
        CrashReport.initCrashReport(this, Store.BUGLY_APPID, BuildConfig.DEBUG, strategy)

        //百川 sdk 暂不接入
//        //必须首先执行这部分代码, 如果在":TCMSSevice"进程中，无需进行云旺（OpenIM）和app业务的初始化，以节省内存;
//        SysUtil.setApplication(this);
//        if (SysUtil.isTCMSServiceProcess(this)) {
//            return;
//        }
////第一个参数是Application Context
////这里的APP_KEY即应用创建时申请的APP_KEY，同时初始化必须是在主进程中
//        if (SysUtil.isMainProcess()) {
//            YWAPI.init(this, Store.AliServiceAppKey)
//        }
        try {
            YmConfig.initNovel(this, "8248")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        initGameSdk()
        //设置全局错误上报，同时防止未处理错误导致崩溃
        RxJavaPlugins.setErrorHandler {
            CrashReport.postCatchedException(it)
        }

        Logger.setDebug(BuildConfig.DEBUG)
        JLibrary.InitEntry(this)
        appViewModelStoreOwner = ViewModelStore()
        viewModelFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
    }


    private fun initGameSdk() {
        TTAdSdk.getAdManager().sdkVersion
        TTAdSdk.init(this,
                TTAdConfig.Builder()
                        .appId("5031608")
                        .useTextureView(false) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                        .appName("趣味星球")
                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_NO_TITLE_BAR)
                        .allowShowNotify(true) //是否允许sdk展示通知栏提示
                        .allowShowPageWhenScreenLock(false) //是否在锁屏场景支持展示广告落地页
                        .debug(BuildConfig.DEBUG) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI, TTAdConstant.NETWORK_STATE_3G, TTAdConstant.NETWORK_STATE_4G) //允许直接下载的网络状态集合
                        .supportMultiProcess(false) //是否支持多进程，true支持
                        .build())

        val cmGameAppInfo = CmGameAppInfo()
        cmGameAppInfo.appId = Store.TINY_GAME_APP_ID                             // GameSdkID，向我方申请
        cmGameAppInfo.appHost = Store.TINY_GAME_APP_HOST   // 游戏host地址，向我方申请

        // 【可选功能】游戏退出时，增加游戏推荐弹窗，提高游戏的点击个数，注释此行可去掉此功能
        cmGameAppInfo.isQuitGameConfirmFlag = true

        // 【必须功能】设置游戏的广告id
        val ttInfo = CmGameAppInfo.TTInfo()
        ttInfo.rewardVideoId = "931608984"   // 激励视频
        ttInfo.fullVideoId = "931608823"     // 全屏视频
        ttInfo.expressBannerId = "931608019" // Banner广告，模板渲染，尺寸：600*150
        ttInfo.expressInteractionId = "931608886" // 插屏广告，模板渲染，尺寸比例 2：3

        // 游戏加载时的插屏广告，广告样式为：插屏广告-原生-自渲染-大图
        // 在2019-7-17后，穿山甲只针对部分媒体开放申请，如后台无法申请到这个广告位，则无需调用代码
        ttInfo.loadingNativeId = "931608108" /*"901121435"*/
        cmGameAppInfo.ttInfo = ttInfo

        CmGameSdk.initCmGameSdk(this, cmGameAppInfo, TinyGameImageLoader, BuildConfig.DEBUG)

    }


    private fun registerActivityLifecycle() {
        var loginActivityCreated = 0
        var mainActivityCreated = 0
        var wxLoginActivityCreated = 0

        registerActivityLifecycleCallbacks(object : ActivityLifeCycleAdapter() {
            var activityCount = 0

            override fun onActivityDestroyed(activity: Activity?) {
                if (activity is LoginFillSmsActivity) loginActivityCreated--
                if (activity is MainActivity) mainActivityCreated--
                if (activity is WxLoginActivity) wxLoginActivityCreated--
                if (activityCount-- == 0)
                    networkViewModel.dispose()
            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {

                if (activity is LoginV2Activity) loginActivityCreated++


                if (loginActivityCreated > 1 && activity is LoginFillSmsActivity)
                    activity.finish()

                if (activity is MainActivity) mainActivityCreated++

                if (mainActivityCreated > 1 && activity is MainActivity)
                    activity.finish()

                if (activity is WxLoginActivity) wxLoginActivityCreated++

                if (wxLoginActivityCreated > 1 && activity is WxLoginActivity)
                    activity.finish()


                activityCount++
            }

        })
    }

    fun getAppViewModelProvider(): ViewModelProvider {

        return ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(this))
    }


}

open class ActivityLifeCycleAdapter : Application.ActivityLifecycleCallbacks {
    override fun onActivityPaused(activity: Activity?) {}

    override fun onActivityResumed(activity: Activity?) {}

    override fun onActivityStarted(activity: Activity?) {}

    override fun onActivityDestroyed(activity: Activity?) {}

    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}

    override fun onActivityStopped(activity: Activity?) {}

    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}

}
